/*
 * ========================================================
 * Copyright(c) 2014 杭州偶尔科技-版权所有
 * ========================================================
 * 本软件由杭州偶尔科技所有, 未经书面许可, 任何单位和个人不得以
 * 任何形式复制代码的部分或全部, 并以任何形式传播。
 * 公司网址
 * 
 * 			http://www.kkkd.com/
 * 
 * ========================================================
 */
package com.simon.mengkou.wxpay;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.util.Xml;

import com.ouertech.android.agm.lib.base.constant.CstCharset;
import com.ouertech.android.agm.lib.base.utils.UtilLog;
import com.ouertech.android.agm.lib.ui.base.BaseUIActivity;
import com.simon.mengkou.R;
import com.simon.mengkou.data.bean.base.NewOrder;
import com.simon.mengkou.data.bean.base.Order;
import com.simon.mengkou.system.constant.CstOuer;
import com.simon.mengkou.system.global.OuerApplication;
import com.simon.mengkou.utils.UtilOuer;
import com.simon.mengkou.utils.image.BitmapUtil;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.xmlpull.v1.XmlPullParser;

import java.io.StringReader;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @author : Zhenshui.Xia
 * @since : 2016/4/14.
 * desc    : 微信支付
 */
public class Wxpay {
    private BaseUIActivity mActivity;
    private NewOrder mOrder;
    PayReq req;
    IWXAPI msgApi;

    Map<String,String> resultunifiedorder;


    public Wxpay(BaseUIActivity activity) {
        mActivity = activity;
        req = new PayReq();
        msgApi = WXAPIFactory.createWXAPI(activity, CstOuer.WECHAT.WECHAT_APP_ID);
    }

    public void pay(NewOrder order) {
        if(!msgApi.isWXAppInstalled()) {
            UtilOuer.toast(mActivity, R.string.common_wx_install);
            return;
        }

        if(!msgApi.isWXAppSupportAPI()) {
            UtilOuer.toast(mActivity, R.string.common_wx_support);
            return;
        }


        mOrder = order;
        GetPrepayIdTask getPrepayId = new GetPrepayIdTask();
        getPrepayId.execute();


    }


    /**
     生成签名
     */

    private String genPackageSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(CstOuer.WECHAT.SECRET);


        String packageSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();
        return packageSign;
    }


    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(CstOuer.WECHAT.SECRET);

        String appSign = MD5.getMessageDigest(sb.toString().getBytes()).toUpperCase();

        return appSign;
    }
    private String toXml(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (int i = 0; i < params.size(); i++) {
            sb.append("<"+params.get(i).getName()+">");


            sb.append(params.get(i).getValue());
            sb.append("</"+params.get(i).getName()+">");
        }
        sb.append("</xml>");

        return sb.toString();
    }


    private class GetPrepayIdTask extends AsyncTask<Void, Void, Map<String,String>> {

        @Override
        protected void onPreExecute() {
            mActivity.setWaitingDialog(true);
        }

        @Override
        protected void onPostExecute(Map<String,String> result) {
            mActivity.setWaitingDialog(false);

            resultunifiedorder=result;
            genPayReq();
            sendPayReq();
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
            mActivity.setWaitingDialog(false);
        }

        @Override
        protected Map<String,String>  doInBackground(Void... params) {

            String url = String.format("https://api.mch.weixin.qq.com/pay/unifiedorder");
            String entity = genProductArgs();

            UtilLog.d(entity);

            byte[] buf = Util.httpPost(url, entity);

            String content = new String(buf);
            UtilLog.d(content);
            Map<String,String> xml=decodeXml(content);

            return xml;
        }
    }

    public Map<String,String> decodeXml(String content) {

        try {
            Map<String, String> xml = new HashMap<String, String>();
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(new StringReader(content));
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {

                String nodeName=parser.getName();
                switch (event) {
                    case XmlPullParser.START_DOCUMENT:

                        break;
                    case XmlPullParser.START_TAG:

                        if("xml".equals(nodeName)==false){
                            //实例化student对象
                            xml.put(nodeName,parser.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                event = parser.next();
            }

            return xml;
        } catch (Exception e) {
            Log.e("orion",e.toString());
        }
        return null;

    }


    private String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }

    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }



    private String genOutTradNo() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000)).getBytes());
    }


    //
    private String genProductArgs() {
        StringBuffer xml = new StringBuffer();

        try {
            String	nonceStr = genNonceStr();

            new String();

            xml.append("</xml>");
            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
            packageParams.add(new BasicNameValuePair("appid", CstOuer.WECHAT.WECHAT_APP_ID));
            packageParams.add(new BasicNameValuePair("body",  mOrder.getStoreList().get(0).getGoodsList().get(0).getTitle()));
            packageParams.add(new BasicNameValuePair("mch_id", CstOuer.WECHAT.PARTNER));
            packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));
            packageParams.add(new BasicNameValuePair("notify_url", "http://www.yiqihitao.com/api/pay/weix"));
            packageParams.add(new BasicNameValuePair("out_trade_no",mOrder.getId()));
            packageParams.add(new BasicNameValuePair("spbill_create_ip", "127.0.0.1"));
            packageParams.add(new BasicNameValuePair("total_fee",
                    String.valueOf(BigDecimal.valueOf(mOrder.getAmount())
                            .multiply(BigDecimal.valueOf(100)).setScale(0, BigDecimal.ROUND_HALF_UP).intValue())));
//            packageParams.add(new BasicNameValuePair("total_fee", "1"));
            packageParams.add(new BasicNameValuePair("trade_type", "APP"));

            String sign = genPackageSign(packageParams);
            packageParams.add(new BasicNameValuePair("sign", sign));


            String xmlstring =toXml(packageParams);

            return new String(xmlstring.getBytes(), CstCharset.ISO_8859_1);


        } catch (Exception e) {
            return null;
        }


    }
    private void genPayReq() {
        req.appId = CstOuer.WECHAT.WECHAT_APP_ID;
        req.partnerId = CstOuer.WECHAT.PARTNER;
        req.prepayId = resultunifiedorder.get("prepay_id");
        req.packageValue = "Sign=WXPay";
        req.nonceStr = genNonceStr();
        req.timeStamp = String.valueOf(genTimeStamp());


        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

        req.sign = genAppSign(signParams);
    }

    private void sendPayReq() {
        msgApi.registerApp(CstOuer.WECHAT.WECHAT_APP_ID);
        msgApi.sendReq(req);
    }


}
